package com.imooc.security.core.validator.code;

import com.imooc.security.core.properties.SecurityProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

@Component
public class ValidateCodeFilter extends OncePerRequestFilter implements InitializingBean {
    @Autowired
    private AuthenticationFailureHandler myAuthenticationFailureHandler;

    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    private Set<String> urls = new HashSet<>();

    @Autowired
    private SecurityProperties securityProperties;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void afterPropertiesSet() throws ServletException {
        super.afterPropertiesSet();
        String[] configUrls = StringUtils.split(securityProperties.getCode().getImage().getUrl(), ",");
        for (String configUrl : configUrls) {
            urls.add(configUrl);
        }

        // 登陆默认需要
        urls.add("/signin/form");
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        boolean needCode = false;
        for (String url : urls) {
            if (antPathMatcher.match(url, request.getRequestURI())) {
                needCode = true;
                break;
            }
        }
        ServletWebRequest servletWebRequest = new ServletWebRequest(request);

        // if (StringUtils.equals(request.getRequestURI(), "/signin/form") && StringUtils.equalsIgnoreCase(request.getMethod(), "post")) {
        if (needCode) {
            try {
                validateVerification(servletWebRequest);
            } catch (ValidateCodeException e) {
                myAuthenticationFailureHandler.onAuthenticationFailure(request, response, e);
                return;
            }
        }
        filterChain.doFilter(request, response);

    }

    private void validateVerification(ServletWebRequest servletWebRequest) throws ServletRequestBindingException {
        ImageCode verificationCode = (ImageCode) sessionStrategy.getAttribute(servletWebRequest, ValidateCodeController.VERYIF_CODE_SESSION_KEY);
        String userInCode = ServletRequestUtils.getStringParameter(servletWebRequest.getRequest(), "imageCode");
        if (StringUtils.isBlank(userInCode)) {
            throw new ValidateCodeException("验证码不能为空");
        }
        if (verificationCode == null) {
            throw new ValidateCodeException("验证码不存在");
        }

        if (verificationCode.isExpire()) {
            sessionStrategy.removeAttribute(servletWebRequest, ValidateCodeController.VERYIF_CODE_SESSION_KEY);
            throw new ValidateCodeException("验证码已过期");
        }

        if (!StringUtils.equals(verificationCode.getCode(), userInCode)) {
            throw new ValidateCodeException("验证码不匹配");
        }


        sessionStrategy.removeAttribute(servletWebRequest, ValidateCodeController.VERYIF_CODE_SESSION_KEY);
    }

    public SessionStrategy getSessionStrategy() {
        return sessionStrategy;
    }

    public void setSessionStrategy(SessionStrategy sessionStrategy) {
        this.sessionStrategy = sessionStrategy;
    }

    public AuthenticationFailureHandler getMyAuthenticationFailureHandler() {
        return myAuthenticationFailureHandler;
    }

    public void setMyAuthenticationFailureHandler(AuthenticationFailureHandler myAuthenticationFailureHandler) {
        this.myAuthenticationFailureHandler = myAuthenticationFailureHandler;
    }

    public SecurityProperties getSecurityProperties() {
        return securityProperties;
    }

    public void setSecurityProperties(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }
}
